package net.hserver.apm.service;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import com.mongodb.util.JSON;
import net.hserver.apm.bean.Info;
import net.hserver.apm.bean.LinkData;
import net.hserver.apm.bean.LinkInfoVo;
import net.hserver.apm.common.entity.LinkInfo;
import net.hserver.apm.config.MongodbConfig;
import net.hserver.apm.util.IpUtil;
import net.hserver.apm.util.LinkTree;
import org.bson.Document;
import org.bson.conversions.Bson;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;

import java.util.*;


@Bean
public class LinkInfoService {

    @Autowired
    private MongoClient mongoClient;


    public List<Document> getStack(String chainId) {
        MongoDatabase database = mongoClient.getDatabase(MongodbConfig.DATA_BASE);
        MongoCollection<Document> linkInfo = database.getCollection("linkInfo");
        Bson bson = null;
        if (chainId != null && chainId.trim().length() > 0) {
            bson = Filters.and(Filters.eq("chainId", chainId));
        }
        MongoCursor<Document> time;
        if (bson == null) {
            time = linkInfo.find().sort(Sorts.descending( "level")).iterator();
        } else {
            time = linkInfo.find(bson).sort(Sorts.descending( "level")).iterator();
        }
        List<Document> data = new ArrayList<>();
        try {
            while (time.hasNext()) {
                data.add(time.next());
            }
        } finally {
            time.close();
        }
        return data;
    }


    public Object getStackChat(String chainId) {
        List<Document> stack = getStack(chainId);
        List<LinkData> data = new ArrayList<>();
        int i = 0;
        for (Document linkInfo : stack) {
            LinkData linkData = new LinkData();
            linkData.setTitle(new Info("方法：" + linkInfo.get("method")));
            List<Info> d = new ArrayList<>();
            d.add(new Info("类：" + linkInfo.get("className")));
            d.add(new Info("参数：" + linkInfo.get("parameterType")));
            d.add(new Info("返回类型：" + linkInfo.get("returnType")));
            d.add(new Info("耗时：" + linkInfo.get("ms") + "/ms"));
            linkData.setData(d);
            linkData.setId(linkInfo.get("level").toString());
            linkData.setSpanId(linkInfo.get("spanId").toString());
            if (i == 0) {
                linkData.setpSpanId("0");
            } else {
                linkData.setpSpanId(linkInfo.get("pSpanId").toString());
            }
            i++;
            data.add(linkData);
        }
        LinkTree menuTree = new LinkTree(data);
        return menuTree.builTree();
    }

}
